import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import request from '@/utils/request'
import RSAEncrypt from '@/utils/common/RSAEncrypt'
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    roles: [],
    permission: { permissionButtons: new Set(), permissionMenus: new Map() }
  }
}
var user = {
  state: getDefaultState(),
  mutations: {
    RESET_STATE: (state) => {
      Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    setPermissionButtons: (state, permissionButtons) => {
      var buttons = new Set()
      permissionButtons.forEach(item => {
        buttons.add(item)
      })
      state.permission.permissionButtons = buttons
    },
    setPermissionMenus: (state, permissionMenus) => {
      var menus = new Map()
      permissionMenus.forEach(item => {
        menus.set(item.code, item)
      })
      state.permission.permissionMenus = menus
    }
  },
  actions: {
    // 用户名登录
    login({ commit }, userInfo) {
      const { username, password } = userInfo
      userInfo.password = RSAEncrypt.encrypt(password)
      userInfo.username = RSAEncrypt.encrypt(username)
      return new Promise((resolve, reject) => {
        request.post('sso/login', {
          username: userInfo.username,
          password: userInfo.password,
          verificationCode: userInfo.verificationCode
        }).then(response => {
          commit('SET_TOKEN', response)
          setToken(response)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 手机登录
    mobileLogin({ commit }, userInfo) {
      const { mobile } = userInfo
      userInfo.mobile = RSAEncrypt.encrypt(mobile)
      return new Promise((resolve, reject) => {
        request.post('sso/mobileLogin', {
          mobile: userInfo.mobile,
          mobileVerificationCode: userInfo.mobileVerificationCode
        }).then(response => {
          commit('SET_TOKEN', response)
          setToken(response)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 生成登录二维码
    generateLoginQRCode({ commit }) {
      return new Promise((resolve, reject) => {
        request.post('sso/getQRImage').then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获得登录二维码状态
    getQRImageStatus({ commit }, params) {
      return new Promise((resolve, reject) => {
        request.post(`sso/getQRImageStatus/${params.imageId}`).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户详情
    getInfo({ commit }) {
      return new Promise((resolve, reject) => {
        request.get('sso/getInfo').then(response => {
          if (response.cacheRoleVos && response.cacheRoleVos.length > 0) { // 验证返回的roles是否是一个非空数组
            const roles = []
            response.cacheRoleVos.forEach((item) => {
              roles.push(item.roleCode)
            })
            commit('SET_ROLES', roles)
          } else {
            Message({
              message: '您还没赋予任何角色，请联系管理员赋予角色',
              type: 'warning',
              duration: 5 * 1000
            })
            reject('getInfo: roles must be a non-null array !')
          }
          commit('SET_USER_INFO', response)
          commit('setPermissionButtons', response.perms)
          commit('setPermissionMenus', response.menuPerms)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出
    logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        request.post('sso/logout').then(() => {
          removeToken()
          resetRouter()
          commit('RESET_STATE')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 用户注册
    userRegister({ commit }, params) {
      return new Promise((resolve, reject) => {
        request.post('sso/register', {
          mobile: params.mobile,
          password: params.password,
          passwordAgain: params.passwordAgain,
          verificationCode: params.verificationCode,
          realName: params.realName
        }).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 检测是否加入组织
    checkJoinOrg({ commit }, invitationCode) {
      return new Promise((resolve, reject) => {
        request.get('sso/checkJoinOrg/' + invitationCode).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 加入组织
    joinOrg({ commit }, params) {
      return new Promise((resolve, reject) => {
        request.post('sso/joinOrg', {
          invitationCode: params.invitationCode,
          realName: params.realName
        }).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 离开组织
    leaveOrg({ commit }, orgId) {
      return new Promise((resolve, reject) => {
        request.post(`sso/leaveOrg/${orgId}`).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 进入组织
    enterOrg({ commit }, orgId) {
      return new Promise((resolve, reject) => {
        request.post(`sso/enterOrg/${orgId}`).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 切换部门
    changeDept({ commit }, deptId) {
      return new Promise((resolve, reject) => {
        request.post(`sso/changeDept/${deptId}`).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 忘记密码
    forgotPassword({ commit }, params) {
      return new Promise((resolve, reject) => {
        request.post('sso/forgotPassword', {
          mobile: params.mobile,
          password: params.password,
          passwordAgain: params.passwordAgain,
          verificationCode: params.verificationCode
        }).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 修改密码
    modifyPassword({ commit }, params) {
      return new Promise((resolve, reject) => {
        request.post('sso/modifyPassword', {
          oldPassword: params.oldPassword,
          newPassword: params.newPassword,
          newPasswordAgain: params.newPasswordAgain,
          verificationCode: params.verificationCode
        }).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 修改头像
    modifyAvatar({ commit }, avatar) {
      return new Promise((resolve, reject) => {
        request.post('sso/modifyAvatar', avatar).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 修改用户名
    modifyUserName({ commit }, username) {
      return new Promise((resolve, reject) => {
        request.post('sso/modifyUserName', username).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 修改手机号
    modifyMobile({ commit }, params) {
      return new Promise((resolve, reject) => {
        request.post('sso/modifyMobile', {
          verificationCode: params.verificationCode,
          newMobile: params.newMobile,
          newVerificationCode: params.newVerificationCode
        }).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 修改邮箱
    modifyEmail({ commit }, params) {
      return new Promise((resolve, reject) => {
        request.post('sso/modifyEmail', {
          verificationCode: params.verificationCode,
          newEmail: params.newEmail,
          emailVerificationCode: params.emailVerificationCode
        }).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 解锁
    unlock({ commit }, password) {
      password = RSAEncrypt.encrypt(password)
      return new Promise((resolve, reject) => {
        request.post('sso/unlock', password).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     * 移除Token
     */
    removeToken({ commit }) {
      return new Promise(resolve => {
        removeToken()
        commit('RESET_STATE')
        resolve()
      })
    },
    /**
     * 重置Token
     */
    resetToken({ dispatch, commit }, token) {
      return new Promise(resolve => {
        setToken(token)
        commit('SET_TOKEN', token)
        dispatch('getInfo')
        resolve()
      })
    }
  }
}
export default user
